# 个人中心相关视图
from flask import current_app
from flask import g, jsonify
from flask import redirect
from flask import render_template
from flask import request
from flask import session

from info import constants
from info import db
from info.models import Category, News
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET
from . import profile_blu


@profile_blu.route('/user_follow')
@user_login_data
def user_follow():
    # 获取页数
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    user = g.user

    follows = []
    current_page = 1
    total_page = 1
    try:
        paginate = user.followed.paginate(p, constants.USER_FOLLOWED_MAX_COUNT, False)
        # 获取当前页数据
        follows = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    user_dict_li = []

    for follow_user in follows:
        user_dict_li.append(follow_user.to_dict())
    data = {"users": user_dict_li, "total_page": total_page, "current_page": current_page}
    return render_template('news/user_follow.html', data=data)

@profile_blu.route('/news_release', methods=["GET", "POST"])
@user_login_data
def news_release():
    """新闻发布"""
    # 1. 判断请求方式，便利查询出分类，发布页面显示
    if request.method == "GET":
        category_li = []
        try:
            categorys = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)

        for category in categorys:
            category = category.to_dict()
            category_li.append(category)

        category_li.pop(0)

        data = {
            "categorys": categorys
        }

        return render_template("news/user_news_release.html", data=data)

    # 2 post请求
    # 2 获取请求参数
    # print("start")
    title = request.form.get("title")
    source = "个人发布"
    digest = request.form.get("digest")
    content = request.form.get("content")
    index_image = request.files.get("index_image")
    category_id = request.form.get("category_id")
# 3 校验请求参数
    # 1.1 判断数据是否有值
    if not all([title, source, digest, content, index_image, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 1.2 尝试读取图片
    try:
        index_image = index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    try:
        key = storage(index_image)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片错误")
    # 4 赋值参数给对象
    news = News()
    news.title = title
    news.digest = digest
    news.source = source
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.category_id = category_id
    news.user_id = g.user.id
    # 1代表待审核状态
    news.status = 1

    # 4. 保存到数据库
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

    # 5 返回发布内容
    print("end")
    return jsonify(errno=RET.OK, errmsg="新闻发布成功")


@profile_blu.route('/collection', methods=["GET", "POST"])
@user_login_data
def collection():
    """后端实现收藏新闻"""
    # 1. 获取页数
    p = request.args.get("p",1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    # 2. 获取请求参数
    user = g.user
    collections = []
    current_page = 1
    total_page = 1
    # 4. 查询参数对应的数据库数据
    try:
        # 进行分页数据查询
        paginate = user.collection_news.paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
        collections = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_page.logger.error(e)

    collection_dict_li = []
    for news in collections:
        collection_dict_li.append(news.to_basic_dict())
    data = {
        "total_page": total_page,
        "current_page": current_page,
        "collections": collection_dict_li
    }
    # 5. 返回查询结果
    return render_template("news/user_collection.html", data=data)





@profile_blu.route('/pass_info', methods=["GET", "POST"])
@user_login_data
def pass_info():
    # 1.判断请求方式
    if request.method == "GET":
        return render_template('news/user_pass_info.html')
    # 2.获取参数
    old_password = request.json.get("old_password")
    new_password = request.json.get("new_password")

    # 3.校验参数,旧密码正确性
    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

    if not g.user.check_passowrd(old_password):
        return jsonify(errno=RET.DATAERR, errmsg="旧密码不正确")

    # 4.修改用户新密码
    g.user.password = new_password

    # 5.返回响应
    return jsonify(errno=RET.OK, errmsg="修改成功")



@profile_blu.route('/pic_info', methods=["GET", "POST"])
@user_login_data
def pic_info():
    """用户头像上传"""
    user = g.user
    if request.method == "GET":
        return render_template('news/user_pic_info.html', data={"user_info": user.to_dict()})

    # 1. 获取到上传的文件
    try:
        avatar_file = request.files.get("avatar").read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="读取文件出错")

    # 2. 再将文件上传到七牛云
    try:
        url = storage(avatar_file)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片错误")

    # 3. 将头像信息更新到当前用户的模型中

    # 设置用户模型相关数据
    user.avatar_url = url
    # 将数据保存到数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存用户数据错误")

    data = {
        "user_info": user.to_dict(),
        "avatar_url": constants.QINIU_DOMIN_PREFIX + url
    }

    return jsonify(errno=RET.OK, errmsg="图片上传成功", data=data)



@profile_blu.route('/base_info', methods=["GET", "POST"])
@user_login_data
def base_info():
    """用户基本信息"""
    # 1. 获取当前登录用户的信息
    print(request.method)
    user = g.user
    if request.method == "GET":
        return render_template('news/user_base_info.html', data={"user_info": user.to_dict()})
    # 2. 获取到传入参数
    data_dict = request.json
    nick_name = data_dict.get("nick_name")
    gender = data_dict.get("gender")
    signature = data_dict.get("signature")

    if not all([nick_name, gender, signature]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
    if gender not in(['MAN', 'WOMAN']):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 3. 更新并保存数据
    user.nick_name = nick_name
    user.gender = gender
    user.signature = signature
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

    # 将 session 中保存的数据进行实时更新
    session["nick_name"] = nick_name

    # 4. 返回响应

    return jsonify(errno=RET.OK, errmsg="更新成功")



@profile_blu.route("/info")
@user_login_data
def info():
    """个人中心的主页面展示"""
    # 1 获取到用户登录的模型
    user = g.user
    if not user:
        redirect("/")
    # 2 返回模型指定内容
    data = {
        "user_info": user.to_dict()
    }

    # 渲染模板
    return render_template("news/user.html", data=data)
